import { createStore } from 'vuex'
import axios from 'axios'
import { Toast } from 'vant'
import persist from 'vuex-persistedstate'
export default createStore({
  state: {
    mainColor: 'orange',
    list: [],
    books: []
  },
  mutations: {
    changeColor(state) {
      // console.log('触发了')
      state.mainColor = '#' + Math.random().toString(16).substr(2, 6);
    },

    getBooks(state, arr) {
      state.list = arr
    },

    addBook(state, item) {
      // console.log({...item});
      let obj = {...item}
     
      let flag = false
      state.books.forEach(el => {
        if(el.id === obj.id) {
          Toast('书架中已有此书')
          flag = true
        }
      })
      if(!flag) {
        state.books.push(obj)
        Toast('添加成功')
      }
    },

    changeBooks(state, books) {
      state.books = books
    }
  },
  actions: {
    async getList({commit}) {
      let data = await axios.get('/data.json')
      // console.log(data)
      commit('getBooks', data.data)
    }
  },
  modules: {
  },

  plugins: [persist()]
})
